package cn.edu.scau.cmi.ema.service;

import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Service;

import org.springframework.transaction.annotation.Transactional;


import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.hibernate.Session;
import cn.edu.scau.cmi.ema.dao.*;
import cn.edu.scau.cmi.ema.domain.*;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import cn.edu.scau.cmi.ema.domain.base.CmiPagination;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;

import java.io.IOException;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.persistence.Query;
import java.util.Iterator;
@Service("FoodsaleaddressService")
@Transactional

public class FoodsaleaddressServiceImpl extends CmiEmaService implements FoodsaleaddressService {
	public FoodsaleaddressServiceImpl() {
	}

	@Transactional
	public Foodsaleaddress saveFoodsaleaddress(Foodsaleaddress foodsaleaddress) {

		if (foodsaleaddress.getId() == null) {
			Address address = addressDAO.findAddressById(foodsaleaddress.getAddress().getId());
			Food food = foodDAO.findFoodById(foodsaleaddress.getFood().getId());
			Unit unit = unitDAO.findUnitById(foodsaleaddress.getUnit().getId());

			Foodsaleaddress existingFoodsaleaddress = foodsaleaddressDAO
					.findFoodsaleaddressByPhysicalPrimaryKey(food.getId(), address.getId(), foodsaleaddress.getDate());

			foodsaleaddress.setAddress(address);
			foodsaleaddress.setFood(food);
			foodsaleaddress.setUnit(unit);

			if (isEquals(foodsaleaddress, existingFoodsaleaddress)) {
				return existingFoodsaleaddress;
			}

			foodsaleaddress = foodsaleaddressDAO.store(foodsaleaddress);
			foodsaleaddressDAO.flush();

		} else {
			Foodsaleaddress existingFoodsaleaddress = foodsaleaddressDAO
					.findFoodsaleaddressByPrimaryKey(foodsaleaddress.getId());

			foodsaleaddress = foodsaleaddressDAO.store(foodsaleaddress);
			foodsaleaddressDAO.flush();
		}

		return foodsaleaddress;
	}

	public void deleteFoodsaleaddress(Foodsaleaddress foodsaleaddress) {
		foodsaleaddressDAO.remove(foodsaleaddress);
		foodsaleaddressDAO.flush();
	}

	@Transactional
	public void deleteFoodsaleaddresss(Set<Integer> deleteFoodsaleaddresssId) {
		Query query = foodsaleaddressDAO.createNamedQuery("deleteFoodsaleaddresssById", -1, -1);
		query.setParameter(1, deleteFoodsaleaddresssId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Foodsaleaddress> loadFoodsaleaddresss() {
		return foodsaleaddressDAO.findAllFoodsaleaddresss();

	}

	@Transactional
	public Set<Foodsaleaddress> loadReferenceFoodsaleaddresss(Set<Foodsaleaddress> foodsaleaddresss) {
		Iterator<Foodsaleaddress> foodsaleaddresssIterator = foodsaleaddresss.iterator();
		Set<Foodsaleaddress> referencedFoodsaleaddresss = new HashSet<>();
		while (foodsaleaddresssIterator.hasNext()) {
			Foodsaleaddress currentFoodsaleaddress = foodsaleaddresssIterator.next();

		}
		return referencedFoodsaleaddresss;
	}

	public Set<Foodsaleaddress> loadFoodsaleaddresssByIdSet(Set<Integer> foodsaleaddressIdSet) {

		Iterator<Integer> foodsaleaddressIdIterator = foodsaleaddressIdSet.iterator();
		Set<Foodsaleaddress> foodsaleaddressSet = new HashSet<>();
		while (foodsaleaddressIdIterator.hasNext()) {
			Integer id = foodsaleaddressIdIterator.next();
			Foodsaleaddress currentFoodsaleaddress = foodsaleaddressDAO.findFoodsaleaddressById(id);
			foodsaleaddressSet.add(currentFoodsaleaddress);
		}
		return foodsaleaddressSet;
	}

	@Transactional
	public List<Foodsaleaddress> findAllFoodsaleaddresss(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Foodsaleaddress>(
				foodsaleaddressDAO.findAllFoodsaleaddresss(startResult, maxRows));
	}

	@Transactional
	public Foodsaleaddress findFoodsaleaddressByPrimaryKey(Integer id) {
		return foodsaleaddressDAO.findFoodsaleaddressByPrimaryKey(id);
	}

	@Transactional
	public Integer countFoodsaleaddresss() {
		return ((Long) foodsaleaddressDAO.createQuerySingleResult("select count(o) from Foodsaleaddress o")
				.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodsaleaddresss(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Foodsaleaddress.class);
		return ((Long) foodsaleaddressDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 * 
	 */
	@Transactional
	public Integer countFoodsaleaddresssByName(String queryName) {
		Query query = foodsaleaddressDAO.createNamedQuery("countFoodsaleaddresssByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countFoodsaleaddresssByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Foodsaleaddress.class);
		Session session = entityManager.unwrap(Session.class);
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadFoodsaleaddressObjectReferencedSet(Foodsaleaddress foodsaleaddress) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();
		if (foodsaleaddress.getAddress() != null) {

			Set<Integer> addressIds = new HashSet<Integer>();
			addressIds.add(foodsaleaddress.getAddress().getId());
			objectReferencedSetMap.put("addressIds", addressIds);
		}
		if (foodsaleaddress.getFood() != null) {

			Set<Integer> foodIds = new HashSet<Integer>();
			foodIds.add(foodsaleaddress.getFood().getId());
			objectReferencedSetMap.put("foodIds", foodIds);
		}
		if (foodsaleaddress.getUnit() != null) {

			Set<Integer> unitIds = new HashSet<Integer>();
			unitIds.add(foodsaleaddress.getUnit().getId());
			objectReferencedSetMap.put("unitIds", unitIds);
		}

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadFoodsaleaddressClassReferencedSet(Foodsaleaddress foodsaleaddress) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("addresss", addressDAO.findAllAddresss());
		classReferencedSetMap.put("foods", foodDAO.findAllFoods());
		classReferencedSetMap.put("units", unitDAO.findAllUnits());

		return classReferencedSetMap;
	}

	public boolean isEquals(Foodsaleaddress foodsaleaddress, Object obj) {
		if (obj == foodsaleaddress)
			return true;
		if (!(obj instanceof Foodsaleaddress))
			return false;
		Foodsaleaddress comparedFoodsaleaddress = (Foodsaleaddress) obj;
		if (!CheckPropertyEqual(foodsaleaddress.getFood().getId(), comparedFoodsaleaddress.getFood().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodsaleaddress.getAddress().getId(), comparedFoodsaleaddress.getAddress().getId())) {
			return false;
		}
		if (!CheckPropertyEqual(foodsaleaddress.getDate(), comparedFoodsaleaddress.getDate())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

